using Domain;
using ErrorCode;
using Microsoft.AspNetCore.Mvc;
using ReadAPI.Controllers.Models;
using SqlSugar;
using System.Data;
using System.Linq.Expressions;
using ReadAPI.Utils;

namespace ReadAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly ISqlSugarClient _db;

        public CustomerController(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 根据ID获取客户信息
        /// </summary>
        [HttpGet("GetById")]
        public async Task<APIResult<Customer>> GetById(int id)
        {
            try
            {
                var customer = await _db.Queryable<Customer>()
                    .Where(c => c.Id == id)
                    .FirstAsync();

                return customer != null 
                    ? new APIResult<Customer> { Code = APIEnum.OK, Msg = "获取成功", Data = customer }
                    : new APIResult<Customer> { Code = APIEnum.Error, Msg = "未找到客户信息", Data = null };
            }
            catch (Exception ex)
            {
                return new APIResult<Customer> { Code = APIEnum.Error, Msg = $"获取客户信息失败：{ex.Message}", Data = null };
            }
        }

        /// <summary>
        /// 获取待分配客户列表
        /// </summary>
        [HttpGet("GetPendingCustomers")]
        public async Task<APIResult<CustomerListModel>> GetPendingCustomers([FromQuery] APIPageRequest paging)
        {
            try
            {
                var query = _db.Queryable<Customer>()
                    .Where(c => c.AssignStatus == "pending");

                // 添加搜索条件
                if (!string.IsNullOrEmpty(paging.Keyword))
                {
                    var safeKeyword = paging.Keyword.Replace("'", "''"); // 转义单引号
                    query = query.Where(c => 
                        SqlFunc.Contains(c.CustomerName, safeKeyword) ||
                        SqlFunc.Contains(c.CustomerCode, safeKeyword) ||
                        SqlFunc.Contains(c.ContactName, safeKeyword) ||
                        SqlFunc.Contains(c.Phone, safeKeyword));
                }

                // 添加排序
                if (!string.IsNullOrEmpty(paging.SortField))
                {
                    // 使用安全的排序字段映射
                    Expression<Func<Customer, object>> orderExpression = paging.SortField.ToLower() switch
                    {
                        "customername" => c => c.CustomerName,
                        "customercode" => c => c.CustomerCode,
                        "contactname" => c => c.ContactName,
                        "phone" => c => c.Phone,
                        "createtime" => c => c.CreateTime,
                        _ => c => c.CreateTime // 默认按创建时间排序
                    };

                    query = paging.SortOrder == "descending"
                        ? query.OrderByDescending(orderExpression)
                        : query.OrderBy(orderExpression);
                }
                else
                {
                    query = query.OrderByDescending(c => c.CreateTime);
                }

                // 分页
                var total = await query.CountAsync();
                var list = await query.Skip((paging.PageIndex - 1) * paging.PageSize)
                    .Take(paging.PageSize)
                    .ToListAsync();

                return new APIResult<CustomerListModel> 
                { 
                    Code = APIEnum.OK, 
                    Msg = "获取成功", 
                    Data = new CustomerListModel { Total = total, List = list }
                };
            }
            catch (Exception ex)
            {
                var detailMessage = $"获取待分配客户列表失败：{ex.Message}\n查询参数：Keyword={paging.Keyword}, SortField={paging.SortField}, PageIndex={paging.PageIndex}, PageSize={paging.PageSize}";
                // 可以添加日志记录
                return new APIResult<CustomerListModel> 
                { 
                    Code = APIEnum.Error, 
                    Msg = detailMessage, 
                    Data = null 
                };
            }
        }

        /// <summary>
        /// 获取已分配客户列表
        /// </summary>
        [HttpGet("GetAssignedCustomers")]
        public async Task<APIResult<CustomerListModel>> GetAssignedCustomers([FromQuery] APIPageRequest paging)
        {
            try
            {
                var query = _db.Queryable<Customer>()
                    .Where(c => c.AssignStatus == "assigned");

                // 添加搜索条件
                if (!string.IsNullOrEmpty(paging.Keyword))
                {
                    query = query.Where(c => c.CustomerName.Contains(paging.Keyword) ||
                                             c.CustomerCode.Contains(paging.Keyword) ||
                                             c.ContactName.Contains(paging.Keyword) ||
                                             c.Phone.Contains(paging.Keyword) ||
                                             c.UserName.Contains(paging.Keyword));
                }

                // 添加排序
                if (!string.IsNullOrEmpty(paging.SortField))
                {
                    // 使用安全的排序字段映射
                    Expression<Func<Customer, object>> orderExpression = paging.SortField.ToLower() switch
                    {
                        "customername" => c => c.CustomerName,
                        "customercode" => c => c.CustomerCode,
                        "contactname" => c => c.ContactName,
                        "phone" => c => c.Phone,
                        "username" => c => c.UserName,
                        "assigntime" => c => c.AssignTime,
                        _ => c => c.AssignTime // 默认按分配时间排序
                    };

                    query = paging.SortOrder == "descending"
                        ? query.OrderByDescending(orderExpression)
                        : query.OrderBy(orderExpression);
                }
                else
                {
                    query = query.OrderByDescending(c => c.AssignTime);
                }

                // 分页
                var total = await query.CountAsync();
                var list = await query.Skip((paging.PageIndex - 1) * paging.PageSize)
                    .Take(paging.PageSize)
                    .ToListAsync();

                return new APIResult<CustomerListModel> 
                { 
                    Code = APIEnum.OK, 
                    Msg = "获取成功", 
                    Data = new CustomerListModel { Total = total, List = list }
                };
            }
            catch (Exception ex)
            {
                return new APIResult<CustomerListModel> 
                { 
                    Code = APIEnum.Error, 
                    Msg = $"获取已分配客户列表失败：{ex.Message}", 
                    Data = null 
                };
            }
        }

        /// <summary>
        /// 下载客户导入模板
        /// </summary>
        [HttpGet("DownloadTemplate")]
        public IActionResult DownloadTemplate()
        {
            try
            {
                // 创建Excel模板
                DataTable dt = new DataTable("客户导入模板");
                dt.Columns.Add("客户名称", typeof(string));
                dt.Columns.Add("客户类别", typeof(string));
                dt.Columns.Add("省份", typeof(string));
                dt.Columns.Add("城市", typeof(string));
                dt.Columns.Add("区县", typeof(string));
                dt.Columns.Add("客户价值", typeof(string));
                dt.Columns.Add("信用等级", typeof(string));
                dt.Columns.Add("联系人姓名", typeof(string));
                dt.Columns.Add("性别", typeof(string));
                dt.Columns.Add("职务", typeof(string));
                dt.Columns.Add("手机号码", typeof(string));
                dt.Columns.Add("办公电话", typeof(string));
                dt.Columns.Add("电子邮箱", typeof(string));
                
                // 添加示例数据
                dt.Rows.Add("示例客户", "零售", "广东省", "深圳市", "南山区", "普通", "高", 
                    "张三", "男", "经理", "13800138000", "0755-12345678", "example@example.com");

                // 使用ExcelHelper导出Excel
                byte[] fileBytes = ExcelHelper.DataTableToExcel(dt);
                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "客户导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest($"下载模板失败：{ex.Message}");
            }
        }
    }
}